package com.example.demo.arithmetic.algorithm.recursion;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * leetcode47
 * 回溯求排列组合
 * 递归
 * abc
 * <p>
 * 对于a 求 bc排列
 */
public class BackTracking3 {

    public static void main(String[] args) {

        int[] nums = {1, 1, 3};
        Arrays.sort(nums);
        System.out.println(permute(nums));
    }

    static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(nums, new boolean[nums.length], new LinkedList<>(), res);
        return res;
    }

    static void dfs(int[] nums, boolean[] visited, LinkedList<Integer> list, List<List<Integer>> res) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            // 找到与他相等的上一个元素 是否被访问过
            if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
                continue;
            }
            if (!visited[i]) {
                list.push(nums[i]);
                visited[i] = true;
                dfs(nums, visited, list, res);
                visited[i] = false;
                list.pop();
            }
        }
    }
}
